<?php
namespace app\apijson\query\operators;

class ReferenceOperator
{
    public static function apply($query, $key, $value, $parentData = [])
    {
        if (preg_match('/^(\w+)@$/', $key, $m)) {
            $field = $m[1];
            if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $field)) {
                throw new \app\apijson\core\ApiJsonException('非法引用字段: ' . $field);
            }
            if (is_string($value) && $value[0] === '/') {
                $ref = explode('/', trim($value, '/'));
                if (count($ref) === 2) {
                    $refTable = $ref[0];
                    $refField = $ref[1];
                    if (isset($parentData[$refTable][$refField])) {
                        $query->where($field, $parentData[$refTable][$refField]);
                    }
                }
            } else {
                $query->where($field, $value);
            }
            return true;
        }
        
        return false;
    }
} 